<?php
namespace app\common\service;


use app\common\model\AddressModel;

class AddressService {
    
    public static function insert($data){
        $addressModel =  AddressModel::instance();
        $id = $addressModel ->insertGetId($data);
        $mid = $data['mid'];
        $type = $data['type'];
        if($data['ifdefault'] == 1){
            self::setDefailt($mid, $type, $id);
        }
        return $id;
    }
    
    public static function update($data){
        $id = $data['id'];
        unset($data['type']);
        unset($data['mid']);
        $addressModel =  AddressModel::instance();
        $addressModel->update($data);
        
        $address = $addressModel->find($id);
        $type = $address['type'];
        $mid = $address['mid'];
        if($data['ifdefault'] == 1){
            self::setDefailt($mid, $type, $id);
        }
    }
    
    public static function setDefailt($mid,$type,$id){
        $addressModel = AddressModel::instance();
        $addressModel-> where('mid',$mid)->where('type',$type)->update(['ifdefault' => 2,'updatetime' => date('Y-m-d H:i:s',time())]);
        $addressModel-> where(array("id"=>$id,"mid"=>$mid))->update(['ifdefault' => 1,'updatetime' => date('Y-m-d H:i:s',time())]);
        
    }
}